package com.shengqin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shengqin.entity.Plan;
import com.shengqin.entity.TestResult;
import com.shengqin.service.ITestResultProcessService;
import com.shengqin.service.ITestResultService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class TestResultProcessServiceImpl implements ITestResultProcessService {

    @Resource
    private ITestResultService testResultService;

    private TestResult findExistingResult(TestResult testResult) {
        QueryWrapper<TestResult> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(TestResult::getPlanId, testResult.getPlanId())
                .eq(TestResult::getPrjName, testResult.getPrjName())
                .eq(TestResult::getStudyCode, testResult.getStudyCode());
        return testResultService.getOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void processTestResult(TestResult testResult, Plan plan, TestResultProcessor processor) {
        TestResult existingResult = findExistingResult(testResult);
        if (existingResult != null) {
            processor.processExistingResult(testResult, existingResult, plan);
        } else {
            processor.saveNewResult(testResult, plan.getId());
        }
    }
}